<script lang="ts" setup>
import { useRoute } from 'vue-router';

import { AuthenticationQrCodeLogin } from '@vben/common-ui';
import { LOGIN_PATH } from '@vben/constants';

import { getWechatQrUuid, postWechatCheckQrUuid } from '#/api/plugin/wechat';
import { useAuthStore } from '#/store';

defineOptions({ name: 'QrCodeLogin' });
const authStore = useAuthStore();
const loading = ref(false);
let interTimer: any = null;
const route = useRoute();
const types: any = {
  wechat: '微信',
};
const text = ref('');
const type: any = computed(() => {
  return route.params?.type ?? '';
});
const subTitle = computed(() => {
  return `请用手机${types[type.value]}扫描二维码登录`;
});
let num = 0;
const qruuid = ref('');
const handleCheckQrUuid = async () => {
  num++;
  try {
    if (num >= 180 && interTimer) {
      clearInterval(interTimer);
      return;
    }
    const {
      msg,
      data: { token },
    } = await postWechatCheckQrUuid({
      q: qruuid.value,
      t: 'admin',
    });
    if (msg === '2') {
      loading.value = true;
    }

    if (msg === '3' && interTimer) {
      clearInterval(interTimer);
      authStore.thirdPartyLogin(token);
    }
  } catch {
    if (interTimer) {
      clearInterval(interTimer);
    }
  }
};

onMounted(async () => {
  if (type.value === 'wechat') {
    const {
      data: { url },
      msg,
    } = await getWechatQrUuid();
    text.value = url;
    qruuid.value = msg;
    if (interTimer) {
      clearInterval(interTimer);
    }
    interTimer = setInterval(() => {
      handleCheckQrUuid();
    }, 1500);
  }
});
</script>

<template>
  <AuthenticationQrCodeLogin
    :loading="loading"
    :login-path="LOGIN_PATH"
    :sub-title="subTitle"
    :text="text"
  />
</template>
